#ifndef __NSQF_FILE_QUEUE_H__
#define __NSQF_FILE_QUEUE_H__

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include <cstdio>
#include <string>
#include <map>

using namespace std;

enum FileInterval{ DAILY = 1, HOURLY = 2, MINUTELY = 3 };

namespace nsfq{

class CFileQueue
{
public:
	CFileQueue( const string& sPath, const string& sPrefix, const string& sPostfix );
	virtual ~CFileQueue();

	int Start();
	int Start( const time_t startTime, const FileInterval fileInterval = HOURLY);
	int Stop();

	void DebugOn() { m_bDebug = true; }
	void DebugOff() { m_bDebug = false; }

protected:
	virtual int HandleLine( const string &sLine ) = 0;

	virtual int AfterOpenFile();
	virtual int AfterCloseFile();

	void init();

	int handle_file( const string &sFileName );
	int open( const string &sFileName );
	bool is_debug_on() { return m_bDebug == true; }

	bool is_first_time(const string &sFileName)
	{
		return m_mapFileStatus.find( sFileName ) == m_mapFileStatus.end();
	}

	bool is_first_open( const string &sFileName )
	{
		if( is_first_time( sFileName ) )
			return false;

		if( m_mapFileStatus[ sFileName ].fd >= 0 )
			return true;
		return false;
	}

	int try_restart();
	void loop();
	void log();
	void clean();
	int sleep();
	int update_current();
	int get_single_interval();
	string get_current_filename();
	string get_last_filename();
	string get_filename( time_t time );

private:
	CFileQueue();
	CFileQueue(const CFileQueue&);
	const CFileQueue & operator=( const CFileQueue &);

private:
	string m_sPath;
	string m_sPrefix;
	string m_sPostfix;
	FileInterval m_FileInterval;
	string m_sCurrentFile;

	time_t m_startTime;
	time_t m_currentTime;

	int m_fd;
	off_t m_fileSize;
	
	bool m_bDebug;

	struct stFileStatus
	{
		int fd;
		time_t modifiedTime;
		struct stat stat;
	};

	map<string, stFileStatus> m_mapFileStatus;

	struct stStatistics
	{
		int file;
		int line;
		int loop;

		stStatistics()
		{
			file = 0;
			line = 0;
			loop = 0;
		}
	};

	stStatistics m_statistics;
};

};
#endif//__NSQF_FILE_QUEUE_H__
